package me.helllp.dake.generator.engine.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import freemarker.template.TemplateException;
import me.helllp.dake.generator.engine.RdbmsGenerator;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.meta.core.SmartType;
import me.helllp.dake.generator.utils.FileAndPathUtils;
import me.helllp.dake.generator.utils.UnderlineToCamelUtils;

import javax.lang.model.element.Modifier;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * mybatis mapper文件生成
 */
public class MapperGenerator extends RdbmsGenerator {
    public MapperGenerator(ProjectMetaData projectMetaData) {
        super(projectMetaData);
    }

    @Override
    public void generator() throws IOException, TemplateException {
        String packageName = getProjectMetaData().getBasePackage() + ".mapper";
        FileAndPathUtils.makePackage(getProjectMetaData().getSrcJavaPath(), packageName);

        getTables().stream().forEach(table -> {
            String name = UnderlineToCamelUtils.underlineToCamel(table.getTableName(), false);

            TypeSpec typeSpec = TypeSpec.interfaceBuilder(name + "Mapper")
                    .addSuperinterface(new SmartType(BaseMapper.class, Arrays.asList(new SmartType(getProjectMetaData().getBasePackage() + ".po", name))).build())
                    .addModifiers(Modifier.PUBLIC)
                    .build();

            JavaFile file = JavaFile.builder(packageName, typeSpec).build();
            try {
                file.writeToFile(new File(getProjectMetaData().getSrcJavaPath()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
